<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <span style="color: red;">注：上述涉及的收入说明可以统一写份说明，但要分类说清楚。 单位：万元
        </span>
        <a-row>
          <a-col :xs="12" :sm="12">
            <a-form-model-item label="年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="year">
              <j-dict-select-tag type="list" v-model="model.year" dictCode="year" placeholder="请选择年度"
                @change="handleYearChange" /> <!-- 新增 change 事件 -->
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="基本收入预算明细表" :key="refKeys[0]" :forceRender="true">
        <j-editable-table :ref="refKeys[0]" :loading="cwJbsrysTable.loading" :columns="cwJbsrysTable.columns"
          :dataSource="cwJbsrysTable.dataSource" :maxHeight="300" :disabled="formDisabled" :rowNumber="true"
          :rowSelection="true" :actionButton="true" :customRender="handleCustomRender" :onBeforeAdd="handleBeforeAdd"
          :onBeforeDelete="handleBeforeDelete" />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>
import { mapState } from 'vuex'
import { FormTypes, getRefPromise, VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
import { validateDuplicateValue } from '@/utils/util'
import { getAction } from '@/api/manage'

export default {
  name: 'CwJbsrysTjForm',
  mixins: [JEditableTableModelMixin],
  components: {},
  data() {
    return {
      labelCol: { xs: { span: 24 }, sm: { span: 5 } },
      wrapperCol: { xs: { span: 24 }, sm: { span: 16 } },
      model: { year: '' }, // 初始为空，由watch同步全局年度
      validatorRules: {
        unit: [{ required: true, message: '请选择单位!' }],
        year: [{ required: true, message: '请选择年度!' }],
      },
      addDefaultRowNum: 1,
      refKeys: ['cwJbsrys'],
      tableKeys: ['cwJbsrys'],
      activeKey: 'cwJbsrys',
      confirmLoading: false,
      defaultItemsAdded: false,
      cwJbsrysTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '项目',
            key: 'project',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
            render: (text, record) => {
              return {
                children: text,
                props: { disabled: record.isTotal || this.formDisabled }
              }
            }
          },
          {
            title: '预计2025年实际',
            key: 'cwSj',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '2026年预算',
            key: 'cwYs',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '测算依据（可另加附页）',
            key: 'csyj',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '排序',
            key: 'paixu',
            type: FormTypes.input,
            width: "20px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },
        ]
      },
      url: {
        add: "/cw/cwJbsrysTj/add",
        edit: "/cw/cwJbsrysTj/edit",
        cwJbsrys: { list: '/cw/cwJbsrysTj/queryCwJbsrysByMainId' },
        getByYear: '/cw/cwJbsrysTj/list'
      },
      isManualChange: false // 标记是否手动修改过表单年度
    }
  },
  props: {
    disabled: { type: Boolean, default: false, required: false }
  },
  computed: {
    formDisabled() { return this.disabled },
    ...mapState({ globalYear: state => state.app.globalYear })
  },
  watch: {
    // 监听全局年度变化，同步到表单（仅当未手动修改时）
    globalYear(newVal) {
      if (!this.isManualChange) {
        this.model.year = newVal
        // 可选：自动触发年度查询，解开注释即可
        // this.handleYearChange(newVal)
      }
    },
    // 监听表单年度变化，标记是否手动修改
    'model.year'(newVal, oldVal) {
      if (oldVal && newVal !== this.globalYear) {
        this.isManualChange = true // 手动修改后，不再同步全局年度
      }
    }
  },
  created() {
    // 初始化时同步全局年度
    this.model.year = this.globalYear
  },
  methods: {
    handleYearChange(selectedYearText) {
      if (!selectedYearText) return; // 若未选择年度，直接返回

      // 从 "xxxx年一上" 中提取纯数字年份（如 "2025年一上" → "2025"）
      const yearMatch = selectedYearText.match(/\d+/); // 匹配字符串中的数字部分
      const selectYear = yearMatch ? yearMatch[0] : ''; // 提取到的纯数字年份（字符串类型）

      if (selectYear) {
        this.updateTableColumnTitles(selectYear); // 调用更新列标题的方法
      }
    },

    // 原有方法：更新表格列标题（无需修改，适配提取后的纯数字年份）
    updateTableColumnTitles(selectYear) {
      const budgetYear = Number(selectYear) + 1; // 预算年份 = 选择年份 +1
      const columns = [...this.cwJbsrysTable.columns]; // 复制原有列配置，避免直接修改原数组

      // 更新 "预计实际" 列标题
      const actualColumn = columns.find(col => col.key === 'cwSj');
      if (actualColumn) {
        actualColumn.title = `预计 ${selectYear} 年实际`; // 拼接纯数字年份
        actualColumn.placeholder = `请输入${actualColumn.title}`;
      }

      // 更新 "预算" 列标题
      const budgetColumn = columns.find(col => col.key === 'cwYs');
      if (budgetColumn) {
        budgetColumn.title = `${budgetYear} 年预算`; // 拼接预算年份
        budgetColumn.placeholder = `请输入${budgetColumn.title}`;
      }

      this.cwJbsrysTable.columns = columns; // 重新赋值更新列配置
    },

    updateTableColumnTitles(selectYear) {
      const budgetYear = Number(selectYear) + 1;
      const columns = [...this.cwJbsrysTable.columns];

      const actualColumn = columns.find(col => col.key === 'cwSj');
      if (actualColumn) {
        actualColumn.title = `预计 ${selectYear} 年实际`;
        actualColumn.placeholder = `请输入${actualColumn.title}`;
      }

      const budgetColumn = columns.find(col => col.key === 'cwYs');
      if (budgetColumn) {
        budgetColumn.title = `${budgetYear} 年预算`;
        budgetColumn.placeholder = `请输入${budgetColumn.title}`;
      }

      this.cwJbsrysTable.columns = columns;
    },

    addBefore() {
      this.cwJbsrysTable.dataSource = [];
      this.defaultItemsAdded = false;
      this.addDefaultItemsIfNotAdded();
    },

    addDefaultItemsIfNotAdded() {
      if (!this.defaultItemsAdded) {
        this.addDefaultItems();
        this.defaultItemsAdded = true;
      }
    },

    addDefaultItems() {
      const defaultItems = [
        { project: '上年结转', cwSj: 0.0, cwYs: 0.0, csyj: '', paixu: 1 },
        { project: ' 在职', cwSj: 0.0, cwYs: 0.0, csyj: '除特殊无法在财政列支的人员经费，可暂以实际预算需求填报财政收入', paixu: 2 },
        { project: ' 其中：住房公积金', cwSj: 0.0, cwYs: 0.0, csyj: '除特殊无法在财政列支的人员经费，可暂以实际预算需求填报财政收入', paixu: 3 },
        { project: ' 离退休', cwSj: 0.0, cwYs: 0.0, csyj: '按预算需求减除社保返还资金差额填报，社保返还资金暂按工资测算表中预计数填列', paixu: 4 },
        { project: ' 日常公用经费', cwSj: 0.0, cwYs: 0.0, csyj: '注明测算标准，暂以上年公用经费财政拨款数为准', paixu: 5 },
        { project: ' 技术服务类收入', cwSj: 0.0, cwYs: 0.0, csyj: '要提供测算依据及说明，分类详细测算', paixu: 6 },
        { project: ' 其他专业业务活动收入', cwSj: 0.0, cwYs: 0.0, csyj: '分项详细说明，附相关项目依据', paixu: 7 },
        { project: ' 科技副产品收入', cwSj: 0.0, cwYs: 0.0, csyj: '需要提供测算依据，包括预计种植面积、品种、产量、售价等', paixu: 8 },
        { project: ' 其他辅助活动收入', cwSj: 0.0, cwYs: 0.0, csyj: '要提供测算依据及说明，分类详细测算', paixu: 9 },
        { project: ' 其他业务收入', cwSj: 0.0, cwYs: 0.0, csyj: '要提供测算依据及说明，分类详细测算', paixu: 10 },
        { project: '利息预算收入', cwSj: 0.0, cwYs: 0.0, csyj: '', paixu: 11 },
        { project: '租金预算收入', cwSj: 0.0, cwYs: 0.0, csyj: '说明出租情况', paixu: 12 },
        { project: '科技成果转化收入', cwSj: 0.0, cwYs: 0.0, csyj: '按预计的当年成果转化收入的80%填列，但要提供计算说明，说明收入来源及计算过程', paixu: 13 },
        { project: '社保返还收入', cwSj: 0.0, cwYs: 0.0, csyj: '社保返还资金暂按工资测算表中离退休预计社保返还数填列', paixu: 14 },
        { project: '其他收入', cwSj: 0.0, cwYs: 0.0, csyj: '分项详细说明，包括耕地补贴，稻谷补贴等', paixu: 15 },
        { project: '其他收入（离退休费差额）', cwSj: 0.0, cwYs: 0.0, csyj: '离退休经费财政缺口部分', paixu: 16 },
        { project: '使用非财政拨款结余', cwSj: 0.0, cwYs: 0.0, csyj: '如使用，写明上年决算余额，在不超额情况下使用', paixu: 17 }
      ];

      this.cwJbsrysTable.dataSource = [...this.cwJbsrysTable.dataSource, ...defaultItems];
    },

    handleCustomRender(text, record, index, column) {
      if (record.isTotal) {
        return {
          props: { disabled: true, readonly: true },
          attrs: { disabled: true, readonly: true },
          class: 'total-row'
        };
      }
      return { props: { disabled: this.formDisabled } }
    },

    handleBeforeDelete(record) {
      if (record.isTotal) {
        this.$message.warning('收入合计行不能删除');
        return false;
      }
      return true;
    },

    handleBeforeAdd() { return true; },

    getAllTable() {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },

    editAfter() {
      this.$nextTick(() => {
        if (this.model.year) {
          // 编辑时，从已有的 model.year 中提取年份，更新列标题
          const yearMatch = this.model.year.match(/\d+/);
          const selectYear = yearMatch ? yearMatch[0] : '';
          if (selectYear) {
            this.updateTableColumnTitles(selectYear);
          }
        }
      })

      if (this.model.id) {
        this.cwJbsrysTable.loading = true;
        const params = { id: this.model.id }
        getAction(this.url.cwJbsrys.list, params).then(res => {
          if (res.success) {
            // 直接使用接口返回的子表数据数组
            this.cwJbsrysTable.dataSource = res.result.records || [];
            this.defaultItemsAdded = true;
          }
        }).finally(() => {
          this.cwJbsrysTable.loading = false;
        })
      } else {
        this.addDefaultItemsIfNotAdded();
      }
    },

    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([]).then(() => {
          resolve(allValues)
        }).catch(e => {
          if (e.error === VALIDATE_NO_PASSED) {
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
      })
    },

    classifyIntoFormData(allValues) {
      const main = Object.assign(this.model, allValues.formValue)
      return { ...main, cwJbsrysList: allValues.tablesValue[0].values }
    },

    validateError(msg) { this.$message.error(msg) },

    close() {
      this.visible = false
      this.$emit('close')
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }
    },

    handleChangeTabs(key) { this.activeKey = key; },
  }
}
</script>

<style scoped>
:deep(.total-row) {
  background-color: #f5f5f5 !important;
}

:deep(.total-row .ant-input) {
  background-color: transparent !important;
  color: #333 !important;
  font-weight: bold !important;
  border: none !important;
  cursor: default !important;
}

:deep(.total-row .ant-input:hover),
:deep(.total-row .ant-input:focus) {
  border: none !important;
  box-shadow: none !important;
}
</style>
